﻿using System;
using System.IO;
using Core;
using UnityEditor;
using UnityEngine;

public static class ExtractAnimFromFbx
{
    [MenuItem("Assets/Mini Tools/Anim/从FBX中提取Anim", false, 301)]
    private static void Main()
    {
        var assetGUIDs = Selection.assetGUIDs;
        if (assetGUIDs is { Length: > 0 })
        {
            foreach (var t in assetGUIDs)
            {
                var asset_path = AssetDatabase.GUIDToAssetPath(t);

                if (File.Exists(asset_path)) continue;

                var assetGUIDsInFolder = AssetDatabase.FindAssets("", new[] { asset_path });

                foreach (var guid in assetGUIDsInFolder)
                {
                    var path = AssetDatabase.GUIDToAssetPath(guid);
                    if (path.ToLower().EndsWith(".fbx") == false)
                    {
                        continue;
                    }

                    ProcessFbx(path);
                }
            }
        }

        if (Selection.gameObjects != null && Selection.gameObjects.Length > 0)
        {
            foreach (var item in Selection.gameObjects)
            {
                var path = AssetDatabase.GetAssetPath(item);
                if (path.ToLower().EndsWith(".fbx") == false) continue;

                ProcessFbx(path);
            }
        }

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

        Debug.Log("处理完成");
    }

    private static void ProcessFbx(string fbxPath)
    {
        if (fbxPath.StartsWith("Assets/Proj/Art") == false)
        {
            Debug.LogError($"Error!! 不能处理Assets/Proj/Art目录之外的文件 path={fbxPath}");
            return;
        }

        var fbxClip = AssetDatabase.LoadAssetAtPath<AnimationClip>(fbxPath);
        if (fbxClip == null) return;

        var fbx_name = Path.GetFileName(fbxPath);
        var index = fbx_name.IndexOf(".", StringComparison.Ordinal);

        var anim_name = fbx_name[..index];
        index = anim_name.IndexOf("@", StringComparison.Ordinal);
        if (index >= 0)
        {
            anim_name = anim_name[(index + 1)..];
        }

        anim_name += ".anim";

        var anim_path = fbxPath.Replace(fbx_name, anim_name);

        anim_path = anim_path.Replace("/Art/", "/Res/");
        anim_path = anim_path.Replace("/Fbx/", "/Anim/");

        Utils.File.CreateDirectoryByFilePath(anim_path);

        var anim_clip = new AnimationClip();
        EditorUtility.CopySerialized(fbxClip, anim_clip);
        AssetDatabase.CreateAsset(anim_clip, anim_path);

        Debug.Log(anim_path + "-完成");
    }
}
